package org.simplecrm;

import java.text.MessageFormat;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

/**
 * Singleton for obtaining multilingual messages
 * through the application for different locales.
 */
public class MessagesBundle {

    private static final String BUNDLE_NAME = "com.resources.Messages";
    private static ResourceBundle RESOURCE_BUNDLE
            = ResourceBundle.getBundle(BUNDLE_NAME);

    /**
     * Changing the locale.
     * @param language language parameter
     */
    public static void setLocale(String language) {

        RESOURCE_BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME, new Locale(language));

    }

    private MessagesBundle() {

    }

    public static MessagesBundle getInstance() {
        return MessagesBundleHolder.INSTANCE;
    }

    private static class MessagesBundleHolder {

        private static final MessagesBundle INSTANCE = new MessagesBundle();

    }

    /**
     * Getting message for current locale.
     *
     * @param key key of message in property file
     * @param params parameters for parametrized messages
     * @return message for current locale
     */
    public String getMsg(String key, String... params) {

        String result = null;

        try {
            result = RESOURCE_BUNDLE.getString(key);
            
            if (params != null) {
                result = MessageFormat.format(result, (Object[]) params);
            }
            
        } catch (MissingResourceException | NullPointerException ex) {
            System.out.println(ex);
        }

        return result;
    }

}
